package cn.pigeon.health.service.impl;

import cn.pigeon.health.dao.CheckGroupDao;
import cn.pigeon.health.entity.PageResult;
import cn.pigeon.health.entity.QueryPageBean;
import cn.pigeon.health.pojo.CheckGroup;
import cn.pigeon.health.service.CheckGroupService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 检查组服务层实现类
 */
@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {
    //注入数据层
    @Autowired
    private CheckGroupDao checkGroupDao;

    /**
     * 添加检查组 和 检查组关联信息
     * @param checkGroup
     */
    public void add(CheckGroup checkGroup,Integer[] checkItems) {
        //添加检查组
        checkGroupDao.add(checkGroup);

        //获得添加后的自增长Id
        Integer checkGroupId = checkGroup.getId();

        //添加检查项关联信息
        addRelations(checkGroupId,checkItems);
    }

    /**
     * 按条件分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        //启用PageHelper助手分页
        PageHelper.startPage(currentPage,pageSize);

        Page<CheckGroup> page = checkGroupDao.findByPage(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        Integer checkGroupId = checkGroup.getId();
        //保存检查组基本信息
        checkGroupDao.edit(checkGroup);
        //先删除原有的关联的检查项信息
        checkGroupDao.deleteRelation(checkGroupId);
        //添加检查项关联信息
        addRelations(checkGroupId,checkitemIds);
    }

    @Override
    public CheckGroup findById(int id) {
        return checkGroupDao.findById(id);
    }

    @Override
    public List<Integer> findCheckItemsWithCheckGroupId(int id) {
        return checkGroupDao.findCheckItemsWithCheckGroupId(id);
    }

    @Override
    public List<CheckGroup> findAllCheckGroups() {
        return checkGroupDao.findAllCheckGroups();
    }

    /**
     * 添加检查组和检查项的关联信息
     * @param checkGroupId
     * @param checkitemIds
     */
    private void addRelations(Integer checkGroupId,Integer[] checkitemIds){
        //循环添加检查项关联信息
        for (Integer checkItemid : checkitemIds) {
            Map<String,Integer> map = new HashMap<String,Integer>();
            map.put("checkGroupId",checkGroupId);
            map.put("checkItemId",checkItemid);
            checkGroupDao.addCheckGroupAndCheckItem(map);
        }
    }
}
